<template>
    <div class="page-container h-100">
      <div class="wrapperform m-b-16">
        <div class="searchbox">
          <el-form :inline="true" :model="form" ref="form" class="demo-form-inline">
            <el-form-item label="设备名称" prop="keywords">
              <el-input v-model="form.keywords" placeholder="设备名称/序列号"></el-input>
            </el-form-item>
            <el-form-item label="状态" prop="state">
              <el-select v-model="form.state" placeholder="请选择">
                <el-option label="全部" value="-1"></el-option>
                <el-option label="在线" value="1"></el-option>
                <el-option label="离线" value="0"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item class="BlankPlaceholder formOperationButtons" label=".">
              <el-button size="small"  type="primary" @click="search">查询</el-button>
              <el-button size="small"  @click="reset">重置</el-button>
            </el-form-item>
          </el-form>

        </div>
      </div>

      <div class=" table-box globalDiv">
        <el-table
            class="devList"
            stripe
            ref="multipleTable"
            :row-key="getRowKeys"
            height="calc(100vh - 305px)"
            :data="tableData"
            @selection-change="handleSelectionChange"
            style="width: 100%">
          <el-table-column
              :reserve-selection="true"
              type="selection"
              width="55">
          </el-table-column>
<!--          产品图-->
          <el-table-column
              prop="date"
              :label="$t('Product picture')">
            <template slot-scope="scope">

              <el-image
                  :class="{'offLine':scope.row.isOnline!=1}"
                  :preview-src-list="[devImgs[scope.row.deviceType]]"
                  style=" height: 40px"
                  :src="devImgs[scope.row.deviceType]"
                  fit="contain"></el-image>
            </template>
          </el-table-column>
<!--          设备名称-->
          <el-table-column
              show-overflow-tooltip
              prop="deviceName"
              :label="$t('Device name')">
            <template slot-scope="scope">
              <span>{{scope.row.deviceName||'-'}}</span>
            </template>
          </el-table-column>
<!--          设备类型-->
          <el-table-column
              prop="address"
              :label="$t('Device type')">
            <template slot-scope="scope">
<!--              <p>{{devOptions[scope.row.deviceType]}}</p>-->
              <span>{{$t(devOptions[scope.row.deviceType].label)}}</span>
            </template>
          </el-table-column>
          <!--          状态-->
          <el-table-column
              prop="address"
              :label="$t('status')">
            <template slot-scope="scope">
<!--              在线-->
              <span class="StatusText successStatusText" v-if="scope.row.isOnline == 1">{{$t('on line')}}</span>
<!--              离线-->
              <span class="StatusText primaryStatusText" v-if="scope.row.isOnline != 1">{{$t('offline')}}</span>
            </template>
          </el-table-column>
          <!--          序列号-->
          <el-table-column
              show-overflow-tooltip
              prop="address"
              :label="$t('Serial number')">
            <template slot-scope="scope">
              <span>{{scope.row.deviceCode||'-'}}</span>
            </template>
          </el-table-column>
          <!--          IP-->
          <el-table-column
              show-overflow-tooltip
              prop="address"
              label="IP">
            <template slot-scope="scope">
              <span>{{scope.row.ip||'-'}}</span>
            </template>
          </el-table-column>
          <el-table-column
              class="tableRightTool"
              label="操作"
              width="200">
            <template slot-scope="scope" class="tableRightIcon">
              <el-link icon="iconfont-KUI icon-wrench tableRightIcon" type="primary" title="操作" :underline="false" @click="operationPop(1, scope.row)"></el-link>
              <el-link icon="iconfont-KUI icon-silders tableRightIcon" type="primary" :title="scope.row.isOnline?$t('Network parameter'):$t('Network parameter')+'：'+$t('This operation is not supported because the device is offline')" :underline="false" :disabled="scope.row.isOnline != 1" @click="handelConfig(scope.row)"></el-link>
              <el-link icon="iconfont-KUI icon-unlink tableRightIcon" type="primary" title="解绑" :underline="false" @click="handelUnbind(scope.row)"></el-link>
              <el-link icon="iconfont-KUI icon-link tableRightIcon" type="primary" title="重绑" :underline="false" @click="operationFn(scope.row)"></el-link>
              <el-link icon="iconfont-KUI icon-network tableRightIcon" type="primary" title="跳转到此设备的配置页面" :underline="false" @click="toConfig(scope.row)"></el-link>
            </template>
          </el-table-column>
        </el-table>
        <div style="padding: 20px">
          <el-button size="small" icon="iconfont-KUI icon-search tableBottomToolIcon" @click="searchDevice">搜索</el-button>
          <el-button size="small" icon="iconfont-KUI icon-plus-circle tableBottomToolIcon" @click="addTableData">添加</el-button>
          <el-button size="small" icon="iconfont-KUI icon-wrench tableBottomToolIcon" v-if="multipleSelection.length" @click="operationPop(2)">批量操作</el-button>
          <el-pagination
              style="display: inline-block;float: right"
              small
              background
              :pager-count="5"
              @size-change="handleSizeChange"
              @current-change="handleRightCurrentChange"
              :current-page.sync="form.pageNumber"
              :page-size="form.pageSize"
              layout="sizes,total, prev, pager, next, jumper"
              :total="formPageTabletotal"
              :page-sizes="[10, 20, 50, 100]"
          ></el-pagination>
        </div>
      </div>

<!--      添加设备弹窗-->
        <addDevice :addFlag.sync='addFlag' v-if="addFlag"></addDevice>
<!--      参数配置-->
        <config :editTableRow='editTableRow' :configFlag.sync='configFlag' v-if="configFlag"></config>
<!--      搜索设备-->
        <search :searchFlag.sync='searchFlag' v-if="searchFlag"></search>
      <!--      操作弹窗-->
      <!-- <operation :operationType="operationType" :operationFlag.sync='operationFlag' v-if="operationFlag"></operation> -->
      <operation :operationType="operationType" :operationRow='operationRow' :operationFlag.sync='operationFlag' v-if="operationFlag"></operation>
      <!--      重新绑定弹窗-->
      <rebind :rebindRow='rebindRow' :rebindFlag.sync='rebindFlag' v-if="rebindFlag"></rebind>
    </div>
</template>

<script>
    import {deviceTypeList} from '@/assets/common/js/utils/deviceConfig.js'
    //  设备管理组件
    import addDevice from './add';
    //  网络参数组件
    import config from './config';
    //  操作
    import operation from './operation.vue';
    import rebind from './rebind.vue';
    // 设备搜索组件
    import search from './search';
    import { sbglDevDelete, sbglDevStartdatabackup, sbglDevRestorebackup, fileShowSaveDialog, fileShowOpenDialog, deviceinfoGetlist, sbglDevSetConfig } from '@/api/sbgl'//引入接口
    export default {
        name: "sbgl_index",
        components: {
            addDevice,
            config,
            search,
          operation,
          rebind
        },
        props: {},
        data() {
            return {
              formPageTabletotal:0,
              rebindFlag:false,
              operationType:1,
              multipleSelection:[],
              deadline4:new Date().getTime()+30000,
              devImgNames:['rn','hm','zjm'],
                searchFlag:false,
              operationFlag:false,
                addFlag:false,
                configFlag:false,
                dialogUploadVisible:null,
                dialogImageUrl:null,
                detailData:null,
                formData:null,
                dialogVisible:false,
                detaildialogVisible:false,
                formAdd: {
                    workOrderJson:{
                        "deviceNumber":"",
                        "repairReason":"",
                        "contacts":"",
                        "contactNumber":""
                    }
                },
                tableData: [],
                // 数据分析
                table_config: {
                    table_tbody: [
                    ],
                    thead: [
                        {label: "序号", prop: "@id", type: "index", width: "100"},
                        // 产品图
                        {label: this.i18n.t('Product picture'),width:"270", prop: "workOrderState", align: "center", type:'function',callback:(row) => {
                                var imgSrc=this.devImgs[row.deviceType]
                                return "<div style='text-align: center'><img src="+imgSrc+" /></div>"
                                // return "<el-image style='width: 100px;height: 100px;' src='"+imgSrc+"' fit='contain'></el-image>"
                            }},
                        // 设备名称
                        {label: this.i18n.t('Device name'), prop: "deviceName",type:'function',callback:(row) => {
                                // return row.deviceName||'-'
                                return row.deviceName||'-'
                            }},
                        // 设备类型
                        {label: this.i18n.t('Device type'), prop: "deviceType",type:'function',callback:(row) => {
                            return this.i18n.t(this.devOptions[row.deviceType].label)
                            }},
                        // 状态
                        {label: this.i18n.t('status'), prop: "isOnline",type:'function',callback:(row) => {
                                return row.isOnline == 1 ? this.i18n.t('on line') : this.i18n.t('offline')
                            }},
                        // 序列号
                        {label: this.i18n.t('Serial number'), prop: "deviceCode",type: "function",callback:(row) => {
                                return row.deviceCode||'-'
                            }},
                        {
                            // 操作
                            label: this.i18n.t('operation'),
                            prop: "operation",
                            // 当前列的类型，不填为直接渲染文本，function 为调用回调函数，operation 为操作按钮，image 为显示图片
                            type: "operation",
                            width: 180,
                            // 按钮的风格，为 true 则显示自定义图标，为 false 显示 按钮样式
                            icon: true,
                            // 图标风格按钮列表
                            iconClass: [
                                {
                                    type: "detail",
                                    class: "iconfont-KUI icon-canshupeizhi",
                                    title: this.i18n.t('Network parameter'),//网络参数
                                    callback: "handelConfig",
                                    customIcon:true,
                                    power: "",
                                },
                                // {
                                //     type: "detail",
                                //     class: "el-icon-document-copy",
                                //     title: "开启备份",
                                //     callback: "handelBackups",
                                //     customIcon:true,
                                //     power: "",
                                // },
                                // {
                                //     type: "detail",
                                //     class: "el-icon-receiving",
                                //     title: "数据恢复",
                                //     callback: "handelRestore",
                                //     customIcon:true,
                                //     power: "",
                                // },
                                {
                                    type: "detail",
                                    class: "iconfont-KUI icon-jiebang1",
                                    title: this.i18n.t('unbind'),//解除绑定
                                    callback: "handelUnbind",
                                    customIcon:true,
                                    power: "",
                                }
                            ],
                        },
                    ],
                    tableButtonArr: [
                        {
                            iconClass: "icon-search iconfont-KUI",
                            btnType: 2,
                            text: this.i18n.t('search'),//搜索
                            callback: "searchDevice",
                            power: "search",
                            customIcon:true
                        },
                        {
                            iconClass: "icon-plus-circle iconfont-KUI",
                            btnType: 2,
                            text: this.i18n.t('Add'),//添加
                            callback: "addTableData",
                            power: "add",
                            customIcon:true
                        }
                    ],
                    // 列表前面是否需要显示 checkbox 框，如要显示 值写成 true
                    checkbox: false,
                    index: true,
                    showPagination: false, // 翻页器
                    // 请求表格数据的 url ，可直接传入
                    // url: 'deviceinfo/getlist',
                    // 请求表格数据的 方式
                    // method: "post",
                    //表格 title 文字
                    tableTitle: false,
                    //是否需要给 th 加 样式boder 如果需要加上addBoderClass 不需要显示空或者不加这个字段配置
                    addBoderClass: "addBoderClass",
                    roleList: [],
                },
                selectRow: [],
                devImgs: [
                    require('@/assets/common/img/dev/rn.png'),
                    require('@/assets/common/img/dev/hm.png'),
                    require('@/assets/common/img/dev/zjm.png'),
                ],
                imgList:null,
                deviceidList:null,
                form:{
                    pageNumber:1,
                    pageSize:10,
                  keywords:null,
                  state:"-1",
                },
                devListInterval:null,
                devOptions:null
            };
        },
        computed: {},
        watch: {},
        beforeDestroy() {
            clearInterval(this.devListInterval)
        },
        mounted() {
          this.devOptions=deviceTypeList
          // 查询设备列表表格
          this.search()


            clearInterval(this.devListInterval)
          this.devListInterval=setInterval(this.search,5000)
        },
        methods: {
          handleRightCurrentChange(val) {
            this.form.pageNumber = val;
            this.search()
          },
          handleSizeChange(val) {
            this.form.pageSize = val
            // this.filterImgToBase64()
            console.log(`每页 ${val} 条`);
            this.search()
          },
          getRowKeys(row){
            return row.id;
          },
          clearTableSelection(){
            // 清除表格选中状态
            this.$refs.multipleTable.clearSelection();
          },
          reset(){
            this.clearTableSelection()
            this.form.pageNumber=1
            this.form.pageSize=10
            this.$refs.form.resetFields();
            this.search()
          },
          search(){
            this.clearTableSelection()
            var params=JSON.parse(JSON.stringify(this.form))
            if (params.state==="-1"){
              params.state=null
            }else{
              params.state*=1
            }
            console.log('查询参数',params);
            // 查询设备列表表格
            this.deviceinfoGetlist(params)
          },
          // 重新绑定
          operationFn(row){
            console.log(row);
            this.rebindFlag=true
            this.rebindRow=row
          },
          toConfig(row){
            console.log(123, row);
            let params = {};
            params.deviceCode = row.deviceCode;
            params.ip = row.ip;
            this.sbglDevSetConfig(params);
            // 确定要打开设备web配置地址吗？
            // this.W.$myConfirm('warning', "确定要打开设备web配置地址吗？")
            //     .then(async _ => {
            //     })
            //     .catch(_ => { });
          },
          handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(this.multipleSelection);
          },
          operationPop(type, row){
            console.log(395, type);
            console.log(396, row);
            this.operationType=type
            this.operationRow = [];
            if (type == 1) {
              this.operationRow[0]=row;
              console.log(397, this.operationRow);
            } else {
              this.operationRow = this.multipleSelection;
              console.log(398, this.operationRow);
            }
            this.operationFlag=true
          },
          sbglDevSetConfig(params){
            sbglDevSetConfig(params).then((res) => {
              console.log(res);
              if (res.code === 200) {
                // 操作成功
                this.W.$tips("success", this.i18n.t('Operation successful'));
                // 关闭弹框
                this.handleClose()
              }
            }).catch(err => {
            }).finally(() => {
            })
          },
          hilarity() {
            console.log('30秒时间已到');
            // this.$notify({
            //   title: "提示",
            //   message: "时间已到",
            //   duration: 0,
            // });
          },
            deviceinfoGetlist(params){
                deviceinfoGetlist(params).then((res) => {
                    if (res.code == 200) {
                      this.formPageTabletotal=res.data.totalCount
                        this.tableData=res.data.values
                        // this.$refs.globalTable.loading_data()
                    }
                }).catch().finally(() => {

                })
            },
            searchTableOnload(){

            },
            // 刷新列表
            parentUpdate(){
                this.search();
            },
            // 恢复备份回调
            sbglDevRestorebackup(params, str){
                sbglDevRestorebackup(params, str).then((res) => {
                    this.G.exportFile(res, '备份' + new Date().toLocaleString())
                    if (res.code === 200) {
                        this.W.$tips("success", '开启备份成功！');
                    }
                }).catch().finally(() => {})
            },
            // 选择保存路径
            fileShowOpenDialog(params, row){
                fileShowOpenDialog(params).then((res) => {
                    if (res.code === 200) {
                        this.sbglDevRestorebackup(row.deviceCode, res.data)
                    }
                }).catch().finally(() => {
                })
            },
            // 恢复
            handelRestore(row){
                let params = {
                    title: "请选择文件路径",
                    defaultPath: "",
                    buttonLabel: "",
                    filters: [
                        {
                            extensions: ['zip', 'rar'],
                            name: ""
                        }
                    ],
                    message: "",
                    nameFieldLabel: "",
                    showsTagField: true
                }
                this.fileShowOpenDialog(params, row)
            },
            // 备份回调
            sbglDevStartdatabackup(params, str){
                sbglDevStartdatabackup(params, str).then((res) => {
                    this.G.exportFile(res, '备份' + new Date().toLocaleString())
                    if (res.code === 200) {
                        this.W.$tips("success", '开启备份成功！');
                        this.parentUpdate();
                    }
                }).catch().finally(() => {})
            },
            // 选择保存路径
            fileShowSaveDialog(params, row){
                fileShowSaveDialog(params).then((res) => {
                    if (res.code === 200) {
                        this.sbglDevStartdatabackup(row.deviceCode, res.data)
                    }
                }).catch().finally(() => {
                })
            },
            // 备份
            handelBackups(row){
                // this.W.$tips('warning', '未实现');
                let params = {
                    title: "请选择文件路径",
                    defaultPath: "",
                    buttonLabel: "",
                    filters: [
                        {
                            extensions: ['zip', 'rar'],
                            name: ""
                        }
                    ],
                    message: "",
                    nameFieldLabel: "",
                    showsTagField: true
                }
                this.fileShowSaveDialog(params, row)
            },
            // 解绑回调
            sbglDevDelete(params){
                sbglDevDelete(params).then((res) => {
                    if (res.code === 200) {
                        // 解绑成功
                        this.W.$tips("success", this.i18n.t('Unbind successfully'));
                        this.parentUpdate();
                    }
                }).catch().finally(() => {
                })
            },
            // 解绑
            handelUnbind(row){
                console.log(row);
                // 确定要解绑?解绑后，此设备将从列表中删除
                this.W.$myConfirm('warning', this.i18n.t('Are you sure to unbind')+' <span style="color: red;font-weight: bold">'+row.deviceName+'</span> ？<br>'+this.i18n.t('After unbinding, this device will be removed from the list!'))
                    .then(async _ => {
                        this.sbglDevDelete(row)
                    })
                    .catch(_ => { });
            },
            // 设置网络参数
            handelConfig(row){
                if(!row.isOnline){
                    // 设备不在线，不支持此操作
                    this.W.$tips('warning', this.i18n.t('This operation is not supported because the device is offline'));
                    return
                }
                this.configFlag=true;
                this.editTableRow = row;
                // console.log(2222);
            },
            searchDevice(){
                this.searchFlag=true
                // this.W.$tips('warning', '未实现22');
            },
            addTableData() {
                // this.title = '新增';
                // this.clearformAdd()//新增前清空
                this.addFlag = true;
            },
            //  表格修改回调
            handelDetail(row) {
                this.detailData=row
                this.detaildialogVisible=true;
            },
            //清空处理
            clearformAdd() {
                this.formAdd= {
                    workOrderJson:{
                        "deviceNumber":"",
                        "repairReason":"",
                        "contacts":"",
                        "contactNumber":""
                    }
                }
            }
        }
    }
</script>

<style scoped lang="scss">
::v-deep .devList .el-table__row .el-table__cell{
  padding: 6px 0;
}
::v-deep .tableRightIcon{
  margin-right: 10px !important;
}
</style>
